package cn.itsource.basic.interceptor;

import cn.itsource.basic.jwt.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = request.getHeader("token");
        if (token != null){
            try{
                JwtUtil.parseJwtToken(token);
                return true;
            }catch (Exception e){
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print("{\"success\":\"false\",\"message\":\"toLogin\"}");
                return false;
            }
        }
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print("{\"success\":\"false\",\"message\":\"toLogin\"}");
        return false;
/*        if (token != null){
            Object obj = redisTemplate.opsForValue().get(token);
            if (obj != null)
                redisTemplate.opsForValue().set(token,obj,30, TimeUnit.MINUTES);
                return true;
        }
        //token 不存在则进入登录页面
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print("{\"success\":\"false\",\"message\":\"toLogin\"}");
        return false;*/
    }
}






























